package com.shawn.example.mvvmdemo.ui

import android.os.Bundle
import android.view.Gravity
import android.view.MenuItem
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.navigation.NavigationBarView
import com.google.android.material.navigation.NavigationView
import com.gyf.immersionbar.ImmersionBar
import com.jetpack.mvvm.lib.base.BaseActivity
import com.jetpack.mvvm.lib.base.BaseFragment
import com.jetpack.mvvm.lib.base.RouterConstant
import com.jetpack.mvvm.lib.base.constants.Constants
import com.jetpack.mvvm.lib.base.extention.extraActivity
import com.jetpack.mvvm.lib.base.utils.AppCommon
import com.jetpack.mvvm.lib.binding.ext.viewBind
import com.shawn.example.mvvmdemo.R
import com.shawn.example.mvvmdemo.databinding.ActivityWanMainBinding
import com.shawn.example.mvvmdemo.databinding.NavHeaderMainBinding
import com.shawn.example.mvvmdemo.databinding.ToolbarBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = RouterConstant.App.PAGE_MAIN)
class WanMainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedListener {
    companion object {
        private const val TAG = "WanMainActivity"
    }

    private val binding: ActivityWanMainBinding by viewBind()

    private val tabIdIndexList = listOf(R.id.action_home, R.id.action_wechat, R.id.action_system, R.id.action_square, R.id.action_project)
    private val fragmentList = arrayOfNulls<BaseFragment>(tabIdIndexList.size)
    private val fragmentRouterList = listOf(RouterConstant.Home.PAGE_HOME, RouterConstant.Home.PAGE_WX, null, null, null)

    //底部 tab 栏默认的 position
    private var mIndex = 0

    private val headerBinding: NavHeaderMainBinding by lazy {
        NavHeaderMainBinding.inflate(layoutInflater)
    }

    private val toolBarBinding: ToolbarBinding by lazy {
        binding.toolbarHeader
    }

    private val nodePID by extraActivity<String>("nodeId")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        observerData()
//        switchFragment(tabIdIndexList.indexOf(R.id.action_home))
        binding.bottomNavigation.selectedItemId = tabIdIndexList.first()
    }

    private fun switchFragment(position: Int) {
        if (position < 0) return
        val transaction = supportFragmentManager.beginTransaction()
        hideFragment(transaction)
        val router = fragmentRouterList[position]
        if (!router.isNullOrBlank()) {
            val targetFragment = fragmentList[position]
            targetFragment?.let {
                transaction.show(it)
            } ?: kotlin.run {
                ARouter.getInstance()
                    .build(router)
                    .navigation()?.let {
                        val fragment = it as BaseFragment
                        fragmentList[position] = fragment
                        transaction.add(R.id.container, fragment, null)
                    }
            }
        }
        mIndex = position
        transaction.commitAllowingStateLoss()
    }

    private fun hideFragment(transaction: FragmentTransaction) {
        fragmentList.forEach {
            it.takeIf { it != null }?.let { fragment ->
                transaction.hide(fragment)
            }
        }
    }

    private fun initView() {
        binding.navView.addHeaderView(headerBinding.root)
        binding.bottomNavigation.let { it ->
            it.setOnApplyWindowInsetsListener(null)
            it.setPadding(0, 0, 0, 0)
            it.selectedItemId = mIndex
            it.labelVisibilityMode = NavigationBarView.LABEL_VISIBILITY_LABELED
            it.setOnItemSelectedListener { menuItem ->
                tabIdIndexList.indexOf(menuItem.itemId)
                    .takeIf { index -> index >= 0 }
                    ?.let { index ->
                        toolBarBinding.tvTitle.text = menuItem.title
                        switchFragment(index)
                    }
                true
            }
        }
        binding.navView.setNavigationItemSelectedListener(this)
        toolBarBinding.toolbar.setNavigationOnClickListener {
            binding.drawerLayout.openDrawer(Gravity.LEFT)
        }
        ImmersionBar.getStatusBarHeight(this).let {
            toolBarBinding.toolbar.apply {
                val updatePaddingTop = paddingTop + it
                setPadding(paddingLeft, updatePaddingTop, paddingRight, paddingBottom)
                val layout = layoutParams
                layout.height += it
                this.layoutParams = layout
            }
        }
    }

    override fun onBackPressed() {
        if (binding.drawerLayout.isOpen) {
            binding.drawerLayout.close()
        } else {
            super.onBackPressed()
        }
    }

    private fun observerData() {

    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_collect -> {
                ARouter.getInstance().build(RouterConstant.LoginRegister.PAGE_REGISTER)
                    .navigation(this, object : NavigationCallback {
                        override fun onFound(postcard: Postcard) {
                        }

                        override fun onLost(postcard: Postcard) {
                        }

                        override fun onArrival(postcard: Postcard?) {
                        }

                        override fun onInterrupt(postcard: Postcard) {
                            val bundle = postcard.extras
                            ARouter.getInstance().build(RouterConstant.LoginRegister.PAGE_LOGIN)
                                .with(bundle)
                                .withString(Constants.ROUTER_PATH, postcard.path)
                                .navigation()

                        }
                    })
            }
            R.id.nav_logout -> {
                if (AppCommon.isUserLogin) {

                } else {
                    ARouter.getInstance().build(RouterConstant.LoginRegister.PAGE_LOGIN)
//                        .withString(Constants.ROUTER_PATH, "shawn test path")
                        .navigation()
                }
            }
        }
        return false
    }
}